var Dataset = require('../models').Dataset;
var Comment = require('../models').Comment;
var marked= require('marked')
var User = require('../models').User;
var CheatsheetProxy = require('../proxy').Cheatsheet;

marked.setOptions({
  highlight: function(code){
    return require('highlight.js').highlightAuto(code).value
  }
});

var markDataset = function(dataset){
  dataset.content = marked(dataset.content)
  return dataset
}

exports.getDataset = function(req,res){
  //console.log(req.session.user)
  var result = {user: req.session.user || null};
  var dsid = req.params.dsid
  var promise = Dataset.findOne({_id: dsid}).populate("comments").exec();
  promise.then(function(dataset){
    dataset = markDataset(dataset)
    result.dataset = dataset
    return res.render('dataset',result)
  })
}

/*增*/
exports.newDataset = function(req, res){
  result = {user: req.session.user}
  res.render('editDataset',result)
}
exports.postDataset = function(req, res){
  var dataset = new Dataset(req.body)
  dataset.save(function(err){
    res.send({status:"ok"})
  })
}

/**
 * 改
 */
exports.editDataset = function(req, res){
  var promise = Dataset.findOne({_id: req.params.dsid}).exec();
  promise.then(function(dataset){
    res.render('editDataset',{dataset:dataset})
  })
}
exports.putDataset = function(req,res){
  var promise = Dataset.findOne({_id: req.body.dsid}).exec();
  promise.then(function(dataset){
    dataset.title = req.body.title;
    dataset.url = req.body.url;
    dataset.description = req.body.description;
    dataset.content = req.body.content;
    dataset.edited_at = Date.now();
    dataset.save(function(err){
      if(!err){
        res.send({status:"ok"})
      }
    })

  })
}

/*删*/
exports.deleteDataset = function(req,res){
  var dsid = req.body.dsid
  Dataset.findOne({_id:dsid}).remove(function(err){
    res.send({status:"ok"})
  })
}

/*评论*/
exports.addComment = function(req, res){
  if(!req.session.user){
    return
  }
  var dsid = req.body.dsid
  var content = req.body.content
  var promise = Dataset.findOne({_id: req.body.dsid}).exec();
  promise.then(function(dataset){
    var comment = new Comment({
      author: req.session.user.name,
      author_hashId: req.session.user.hashId,
      content: content
    })
    comment.save(function(err){
      if(!err){
        dataset.comments.push(comment._id)
        dataset.save(function(err){
          if(!err){
            res.send({status:"ok",yourname:req.session.user.name})
          }
        })
      }
    })
  })
}
